package bb.lanxing.device.thirdpart.gpx

import android.view.View
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.activityViewModels
import bb.lanxing.R
import bb.lanxing.databinding.FragmentGpxMapPreviewBinding
import bb.lanxing.fragment.BaiduMapFragment
import bb.lanxing.fragment.base.BaseMapFragment
import bb.lanxing.lib.kt.model.geo.IGeoPoint
import bb.lanxing.model.map.GeoBounds
import bb.lanxing.model.map.GeoPoint
import bb.lanxing.mvvm.base.BaseDBFragment
import bb.lanxing.util.MapUtil
import bb.lanxing.view.WayPointIndicator
import com.baidu.mapapi.map.Marker
import com.baidu.mapapi.map.Polyline
import com.baidu.mapapi.model.LatLng
import io.ticofab.androidgpxparser.parser.domain.Gpx
import io.ticofab.androidgpxparser.parser.domain.WayPoint
import kotlin.jvm.internal.Intrinsics

class GPXPreviewMapFragment :
    BaseDBFragment<FragmentGpxMapPreviewBinding>(R.layout.fragment_gpx_map_preview),
    BaseMapFragment.InitListener {
    private var baiduMapFragment: BaseMapFragment? = null
    private var selectedMarker: Marker? = null
    private var moveFromUser = false
    private val viewModel: GPXImportViewModel by activityViewModels()


    override fun initView(binding: FragmentGpxMapPreviewBinding) {
        val beginTransaction = parentFragmentManager.beginTransaction()
        val newInstance = BaiduMapFragment.newInstance(40.6974034, -74.1197638, false, 16.0f, 1, 0)
        newInstance.setInitListener(this)
        beginTransaction.replace(R.id.map_container, newInstance, "GPXPreviewMapFragment")
            .commitAllowingStateLoss()
    }

    override fun onViewReady(fragment: BaseMapFragment) {
        this.baiduMapFragment = fragment
        viewModel.getGpx().observe(this) { gpx ->
            drawGPX(gpx)
        }
    }

    fun zomeToLatLng(iGeoPoint: IGeoPoint, z: Boolean) {
        this.moveFromUser = z
        baiduMapFragment?.moveTo(iGeoPoint.getLatitude(), iGeoPoint.getLongitude())
    }

    fun moveToLatLng(iGeoPoint: IGeoPoint, z: Boolean) {
        this.moveFromUser = z
        baiduMapFragment?.moveTo(iGeoPoint.latitude, iGeoPoint.longitude)
    }

    override fun onResume() {
        super.onResume()
        val value: Gpx? = viewModel.getGpx().getValue()
        value?.let {
            drawGPX(it)
        }
    }

    private fun drawGPX(gpx: Gpx) {
        val wayPointIndicator: WayPointIndicator? =
            if (binding != null) binding.mapCenterIndicator else null
        if (wayPointIndicator != null) {
            wayPointIndicator.visibility = View.GONE
        }
        selectedMarker = null
        baiduMapFragment?.clearOverlay(1)
        moveFromUser = false
        val wayPointIndicator2 = WayPointIndicator(requireContext())
        wayPointIndicator2.setSize(16.0f, 23.0f)
        val points = GPXextKt.getPoints(gpx)
        if (points.isNotEmpty()) {
            for (list in points) {
                val baseMapFragment2 = this.baiduMapFragment
                baseMapFragment2?.drawLine(
                    1, list, ResourcesCompat.getColor(
                        resources, R.color.common_red, null
                    ), true
                )
                wayPointIndicator2.setUp(0, false, true, true)
                val baseMapFragment3 = this.baiduMapFragment
                baseMapFragment3?.drawMarker(
                    1, GeoPoint(
                        0,
                        list.first().latitude,
                        list.first().longitude
                    ), MapUtil.convertView(wayPointIndicator2.rootView), null as String?, 0.5f, 1.0f
                )
                wayPointIndicator2.setEnd()
                val baseMapFragment4 = this.baiduMapFragment
                baseMapFragment4?.drawMarker(
                    1, GeoPoint(
                        0,
                        list.last().latitude,
                        list.last().longitude
                    ), MapUtil.convertView(wayPointIndicator2.rootView), null as String?, 0.5f, 1.0f
                )
            }
        }
        val wayPoints = gpx.wayPoints
        var i = 0
        for (obj in wayPoints) {
            val i2 = i + 1
            if (i < 0) {
                throw IndexOutOfBoundsException()
            }
            val wayPoint = obj as WayPoint
            wayPointIndicator2.setUp(i, false, true, true)
            val baseMapFragment5 = this.baiduMapFragment
            if (baseMapFragment5 != null) {
                val latitude = wayPoint.latitude
                val longitude = wayPoint.longitude
                baseMapFragment5.drawMarker(
                    1,
                    GeoPoint(0, latitude, longitude),
                    MapUtil.convertView(wayPointIndicator2.rootView),
                    null as String?,
                    0.5f,
                    1.0f
                )
            }
            i = i2
        }
        moveToRouteBounds()
    }

    private fun moveToRouteBounds() {
        var emptyList: List<LatLng>? = null
        var overlay: List<Any>? = null
        this.moveFromUser = false
        val baseMapFragment = this.baiduMapFragment
        if (baseMapFragment == null || (baseMapFragment.getOverlay(1).also {
                overlay = it
            }) == null) {
            emptyList = emptyList()
        } else {
            overlay?.let {
                val arrayList = ArrayList<Polyline>()
                for (obj in it) {
                    if (obj is Polyline) {
                        arrayList.add(obj)
                    }
                }
                val arrayList2 = ArrayList<LatLng>()
                for (polyline in arrayList) {
                    val points = polyline!!.points
                    points?.let { point ->
                        arrayList2.addAll(point)
                    }
                }
                emptyList = arrayList2
            }
        }
        emptyList?.let {
            if (it.size == 1) {
                val fromCommon = GeoPoint.fromCommon(
                    it.first().latitude,
                    it.first().longitude
                )
                Intrinsics.checkNotNullExpressionValue(
                    fromCommon, "fromCommon(point.first()… point.first().longitude)"
                )
                zomeToLatLng(fromCommon, false)
                return
            }
            val builder: GeoBounds.Builder = GeoBounds.Builder()
            for (latLng in it) {
                builder.include(latLng.latitude, latLng.longitude)
            }
            val baseMapFragment2 = this.baiduMapFragment
            baseMapFragment2?.displayBound(builder.build(2))
        }
    }
}